/*
 * @lc app=leetcode.cn id=1122 lang=typescript
 *
 * [1122] 数组的相对排序
 */

// @lc code=start
function relativeSortArray(arr1: number[], arr2: number[]): number[] {
    const mapper = arr2.reduce((map, cur, index) => {
        return map.set(cur, index);
    }, new Map<number, number>());

    const [head, tail] = arr1.reduce(
        (col, cur) => {
            if (mapper.has(cur)) {
                col[0].push(cur);
            } else {
                col[1].push(cur);
            }
            return col;
        },
        [[], []] as number[][]
    );
    return [
        ...head.sort((a, b) => mapper.get(a)! - mapper.get(b)!),
        ...tail.sort((a, b) => a - b),
    ];
}
// @lc code=end
